import React, { useEffect } from 'react';
import { Form, Select, Slider, Switch, Space, Typography, Divider, Button, Empty, Tag } from 'antd';
import { SettingOutlined, ExclamationCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useConversationStore } from '../../../stores/conversation.store';
import { useModelConfigStore } from '../../../stores/model-config.store';
import { Link } from 'react-router-dom';
import './style.css';

const { Title, Text } = Typography;
const { Option } = Select;

const ConversationSettings: React.FC = () => {
  const { settings, updateSettings } = useConversationStore();
  const { configs, loading, loadConfigs } = useModelConfigStore();
  const [form] = Form.useForm();
  
  useEffect(() => {
    loadConfigs();
  }, [loadConfigs]);

  // 获取可用的激活模型（包括unknown状态，让用户自己决定是否使用）
  const availableModels = configs.filter(c => c.isActive === true);
  
  // 分类模型
  const healthyModels = availableModels.filter(c => c.status === 'healthy');
  const unknownModels = availableModels.filter(c => c.status === 'unknown');
  const unhealthyModels = availableModels.filter(c => c.status === 'unhealthy');

  const handleSettingChange = (changedValues: any) => {
    updateSettings(changedValues);
  };

  return (
    <div className="conversation-settings">
      <Form
        form={form}
        layout="vertical"
        initialValues={settings}
        onValuesChange={handleSettingChange}
      >
        <Title level={5}>模型设置</Title>
        
        <Form.Item
          name="model"
          label="AI 模型"
        >
          <Select 
            loading={loading}
            placeholder="选择AI模型"
            notFoundContent={
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={
                  <span>
                    暂无可用模型
                    <br />
                    <Link to="/model-config">
                      <Button type="link" icon={<SettingOutlined />} size="small">
                        前往配置模型
                      </Button>
                    </Link>
                  </span>
                }
              />
            }
          >
            {/* 健康的模型 */}
            {healthyModels.length > 0 && (
              <Select.OptGroup label="可用模型">
                {healthyModels.map(config => (
                  <Option 
                    key={config.id} 
                    value={config.id}
                  >
                    <Space>
                      <CheckCircleOutlined style={{ color: '#52c41a' }} />
                      {config.displayName || config.modelName}
                      {config.providerName && ` (${config.providerName})`}
                    </Space>
                  </Option>
                ))}
              </Select.OptGroup>
            )}
            
            {/* 未测试的模型 */}
            {unknownModels.length > 0 && (
              <Select.OptGroup label="待测试模型（需要先测试连接）">
                {unknownModels.map(config => (
                  <Option 
                    key={config.id} 
                    value={config.id}
                  >
                    <Space>
                      <ExclamationCircleOutlined style={{ color: '#faad14' }} />
                      {config.displayName || config.modelName}
                      {config.providerName && ` (${config.providerName})`}
                      <Tag color="orange" style={{ marginLeft: 4 }}>需测试</Tag>
                    </Space>
                  </Option>
                ))}
              </Select.OptGroup>
            )}
            
            {/* 不健康的模型（显示但不推荐） */}
            {unhealthyModels.length > 0 && (
              <Select.OptGroup label="不可用模型">
                {unhealthyModels.map(config => (
                  <Option 
                    key={config.id} 
                    value={config.id}
                    disabled
                  >
                    <Space>
                      <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
                      {config.displayName || config.modelName}
                      {config.providerName && ` (${config.providerName})`}
                      <Tag color="red" style={{ marginLeft: 4 }}>离线</Tag>
                    </Space>
                  </Option>
                ))}
              </Select.OptGroup>
            )}
          </Select>
        </Form.Item>
        
        {availableModels.length === 0 && (
          <Link to="/model-config">
            <Button type="dashed" icon={<SettingOutlined />} block>
              配置AI模型
            </Button>
          </Link>
        )}

        <Form.Item
          name="temperature"
          label={
            <Space>
              <span>创造性</span>
              <Text type="secondary" style={{ fontSize: 12 }}>
                ({settings.temperature || 0.7})
              </Text>
            </Space>
          }
        >
          <Slider
            min={0}
            max={1}
            step={0.1}
            marks={{
              0: '精确',
              0.5: '平衡',
              1: '创造'
            }}
          />
        </Form.Item>

        <Form.Item
          name="maxTokens"
          label={
            <Space>
              <span>最大长度</span>
              <Text type="secondary" style={{ fontSize: 12 }}>
                ({settings.maxTokens || 2000} tokens)
              </Text>
            </Space>
          }
        >
          <Slider
            min={500}
            max={4000}
            step={100}
            marks={{
              500: '500',
              2000: '2000',
              4000: '4000'
            }}
          />
        </Form.Item>

        <Divider />

        <Title level={5}>显示设置</Title>

        <Form.Item
          name="streamResponse"
          label="流式响应"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="showTimestamp"
          label="显示时间戳"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="enableMarkdown"
          label="Markdown 渲染"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="enableCodeHighlight"
          label="代码高亮"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Divider />

        <Title level={5}>快捷键</Title>

        <div className="shortcut-list">
          <div className="shortcut-item">
            <Text>发送消息</Text>
            <Text type="secondary" keyboard>Ctrl + Enter</Text>
          </div>
          <div className="shortcut-item">
            <Text>新建对话</Text>
            <Text type="secondary" keyboard>Ctrl + N</Text>
          </div>
          <div className="shortcut-item">
            <Text>清空对话</Text>
            <Text type="secondary" keyboard>Ctrl + Shift + D</Text>
          </div>
        </div>
      </Form>
    </div>
  );
};

export default ConversationSettings;